<?php
namespace jimu;

/**
 * 获取请求的变量
 * author william
 * Class Request
 */
final class Request{
    /**
     * 获取get变量
     * @param $key           key
     * @param $default_value default value
     * return array || string
     */
    public static function get($key='',$default_value='')
    {
        if($key == ''){
            $vars = safe_escape($_GET);
        }else{
            $vars = isset($_GET[$key]) ? safe_escape($_GET[$key]) :$default_value;
        }
        return $vars;
    }

    /**
     * 获取post变量
     * @param $key           key
     * @param $default_value default value
     * return array || string
     */
    public static function post($key='',$default_value='')
    {
        if($key == ''){
            $vars = safe_escape($_POST);
        }else{
            $vars = isset($_POST[$key]) ? safe_escape($_POST[$key]) : $default_value;
        }
        return $vars;
    }

    /**
     * 获取cookie变量,
     * @param $key           key
     * @param $default_value default value
     * return array || string
     */
    public static function cookie($key='',$default_value='')
    {
        if($key == ''){
            $vars = safe_escape($_COOKIE);
        }else{
            $vars = isset($_COOKIE[$key]) ? safe_escape($_COOKIE[$key]) : $default_value;
        }
        return $vars;
    }
    
    /**
     * 建立POST请求，以表单HTML形式构造（默认）
     * @param array $params 请求参数数组
     * @param $action
     * @param string $encode
     * @param string $method
     * @return string 提交表单HTML文本
     */
    public function buildForm($params, $action, $encode = 'utf-8', $method='post')
    {
        $encode = strtolower($encode);
        header("Content-type:text/html;charset={$encode}");
        //待请求参数数组
        $sHtml = "<form style='display:none;' id='buildFormSubmit' name='buildFormSubmit' action='" . $action . "' method='{$method}'>";
        foreach ($params as $key => $val) {
            $sHtml .= "<input type='hidden' name='" . $key . "' value='" . $val . "'/>";
        }
        //submit按钮控件请不要含有name属性
        $sHtml = $sHtml . "<input type='submit' value='btn'></form>";
        $sHtml = $sHtml . "<script>document.forms['buildFormSubmit'].submit();</script>";
        return $sHtml;
    }

    public static function is_post()
    {
        return isset($_SERVER['REQUEST_METHOD']) && strtoupper($_SERVER['REQUEST_METHOD'])=='POST';
    }

    public static function is_ajax()
    {
        return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtoupper($_SERVER['HTTP_X_REQUESTED_WITH'])=='XMLHTTPREQUEST';
    }

}